package sg.edu.nus.comp.qa.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.sf.extjwnl.JWNL;
import net.sf.extjwnl.JWNLException;
import net.sf.extjwnl.data.IndexWord;
import net.sf.extjwnl.data.Synset;
import net.sf.extjwnl.data.Word;
import net.sf.extjwnl.dictionary.Dictionary;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WordNetDictionary {
	private static Log LOGGER = LogFactory.getLog(WordNetDictionary.class);
	private static String DICT_PROPERTY_FILE = "target/classes/file_properties.xml";
	private static WordNetDictionary SINGLETON = new WordNetDictionary();
	
	public static void init() throws FileNotFoundException, JWNLException{		
		JWNL.initialize(new FileInputStream(new File(DICT_PROPERTY_FILE)));
		LOGGER.info("Wordnet Dictionary Initialized");
	}

	public boolean isWordsEqual(String stringA, String stringB) {
		try {
			Collection<IndexWord> words = Dictionary.getInstance().lookupAllIndexWords(stringA).getIndexWordCollection();
			for(IndexWord word: words){
				List<Synset> synsets = word.getSenses();
				for(Synset synset : synsets){
					List<Word> synWords = synset.getWords();
					for(Word synWord:synWords){
						if(synWord.getLemma().equals(stringB))
							return true;
					}
				}
			}
			return false;
		} catch (JWNLException e) {
			LOGGER.error("Error in look up word "+stringA, e);
			return false;
		}
	}
	
	public List<String> getSynonyms(String input){
		try {
			Collection<IndexWord> words = Dictionary.getInstance().lookupAllIndexWords(input).getIndexWordCollection();
			List<String> synonyms = new ArrayList<String>();
			for(IndexWord word: words){
				List<Synset> synsets = word.getSenses();
				for(Synset synset : synsets){
					List<Word> synWords = synset.getWords();
					for(Word synWord:synWords){
						synonyms.add(synWord.getLemma());				
					}
				}
			}
			return synonyms;
		} catch (JWNLException e) {
			LOGGER.error("Error in look up word "+ input, e);
			return null;
		}
	}

	public static WordNetDictionary getDictionary() {
		return SINGLETON;
	}
}
